<template>
  <div class="article-container">
    <!-- 顶部搜索和分类 -->
    <div class="article-header">
      <div class="search-section">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索文章..."
          class="search-input"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button icon="Search" @click="handleSearch" />
          </template>
        </el-input>
      </div>
      <div class="category-tabs">
        <el-button 
          v-for="category in categories"
          :key="category.id"
          :type="selectedCategory === category.id ? 'primary' : 'default'"
          @click="selectCategory(category.id)"
          size="small"
        >
          {{ category.name }}
        </el-button>
      </div>
    </div>

    <!-- 文章列表 -->
    <div class="article-list">
      <div 
        v-for="article in articles"
        :key="article.id"
        class="article-card"
        @click="goToArticleDetail(article.id)"
      >
        <div class="article-cover">
          <el-image
            :src="article.coverImage || '/default-article.jpg'"
            fit="cover"
            class="cover-image"
          />
        </div>
        <div class="article-content">
          <h3 class="article-title">{{ article.title }}</h3>
          <p class="article-summary">{{ article.summary }}</p>
          <div class="article-meta">
            <div class="meta-left">
              <el-avatar :size="24" :src="article.authorAvatar" />
              <span class="author">{{ article.author }}</span>
              <span class="publish-time">{{ formatTime(article.publishTime) }}</span>
            </div>
            <div class="meta-right">
              <span class="view-count">
                <el-icon><View /></el-icon>
                {{ article.viewCount }}
              </span>
              <span class="like-count">
                <el-icon><Star /></el-icon>
                {{ article.likeCount }}
              </span>
            </div>
          </div>
          <div class="article-tags">
            <el-tag 
              v-for="tag in article.tags"
              :key="tag"
              size="small"
              type="info"
            >
              {{ tag }}
            </el-tag>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载更多 -->
    <div v-if="hasMore" class="load-more">
      <el-button @click="loadMore" :loading="loading">加载更多</el-button>
    </div>

    <!-- 热门文章侧边栏 -->
    <div class="sidebar">
      <el-card>
        <template #header>
          <span>热门文章</span>
        </template>
        <div class="hot-articles">
          <div 
            v-for="(article, index) in hotArticles"
            :key="article.id"
            class="hot-article-item"
            @click="goToArticleDetail(article.id)"
          >
            <span class="rank">{{ index + 1 }}</span>
            <div class="hot-article-info">
              <h4>{{ article.title }}</h4>
              <p>{{ article.viewCount }}次阅读</p>
            </div>
          </div>
        </div>
      </el-card>

      <el-card style="margin-top: 16px;">
        <template #header>
          <span>热门标签</span>
        </template>
        <div class="hot-tags">
          <el-tag 
            v-for="tag in hotTags"
            :key="tag.name"
            @click="searchByTag(tag.name)"
            style="margin: 4px; cursor: pointer;"
          >
            {{ tag.name }}
          </el-tag>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { 
  getArticleList, 
  getArticleCategories, 
  searchArticles,
  getHotArticles,
  getHotTags
} from '@/api/article'

const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const selectedCategory = ref(null)
const categories = ref([{ id: null, name: '全部' }])
const articles = ref([])
const hotArticles = ref([])
const hotTags = ref([])
const loading = ref(false)
const hasMore = ref(true)

// 分页参数
const pagination = reactive({
  page: 1,
  size: 10
})

// 获取文章分类
const getCategories = async () => {
  try {
    const response = await getArticleCategories()
    if (response.code === 200) {
      categories.value = [{ id: null, name: '全部' }, ...response.data]
    }
  } catch (error) {
    console.error('获取分类失败:', error)
  }
}

// 获取文章列表
const getArticles = async (reset = false) => {
  if (loading.value) return
  
  loading.value = true
  try {
    const params = {
      page: reset ? 1 : pagination.page,
      size: pagination.size,
      categoryId: selectedCategory.value
    }
    
    const response = await getArticleList(params)
    if (response.code === 200) {
      const newArticles = response.data.records || []
      if (reset) {
        articles.value = newArticles
        pagination.page = 1
      } else {
        articles.value.push(...newArticles)
      }
      
      hasMore.value = newArticles.length === pagination.size
      if (!reset) {
        pagination.page++
      }
    }
  } catch (error) {
    console.error('获取文章列表失败:', error)
    ElMessage.error('获取文章列表失败')
  } finally {
    loading.value = false
  }
}

// 获取热门文章
const loadHotArticles = async () => {
  try {
    const response = await getHotArticles(10)
    if (response.code === 200) {
      hotArticles.value = response.data
    }
  } catch (error) {
    console.error('获取热门文章失败:', error)
  }
}

// 获取热门标签
const loadHotTags = async () => {
  try {
    const response = await getHotTags(20)
    if (response.code === 200) {
      hotTags.value = response.data
    }
  } catch (error) {
    console.error('获取热门标签失败:', error)
  }
}

// 搜索文章
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    getArticles(true)
    return
  }
  
  loading.value = true
  try {
    const response = await searchArticles(searchKeyword.value, {
      page: 1,
      size: pagination.size
    })
    if (response.code === 200) {
      articles.value = response.data.records || []
      hasMore.value = false
    }
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败')
  } finally {
    loading.value = false
  }
}

// 选择分类
const selectCategory = (categoryId) => {
  selectedCategory.value = categoryId
  searchKeyword.value = ''
  getArticles(true)
}

// 按标签搜索
const searchByTag = (tag) => {
  searchKeyword.value = tag
  handleSearch()
}

// 加载更多
const loadMore = () => {
  getArticles()
}

// 跳转到文章详情
const goToArticleDetail = (articleId) => {
  router.push(`/article/${articleId}`)
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleDateString()
}

// 页面加载
onMounted(() => {
  getCategories()
  getArticles(true)
  loadHotArticles()
  loadHotTags()
})
</script>

<style lang="scss" scoped>
.article-container {
  display: grid;
  grid-template-columns: 1fr 300px;
  gap: 20px;
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.article-header {
  grid-column: 1 / -1;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  
  .search-section {
    margin-bottom: 16px;
    
    .search-input {
      max-width: 400px;
    }
  }
  
  .category-tabs {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
  }
}

.article-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.article-card {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  cursor: pointer;
  transition: transform 0.3s, box-shadow 0.3s;
  display: flex;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
  }
  
  .article-cover {
    width: 200px;
    height: 150px;
    
    .cover-image {
      width: 100%;
      height: 100%;
    }
  }
  
  .article-content {
    flex: 1;
    padding: 16px;
    display: flex;
    flex-direction: column;
    
    .article-title {
      font-size: 18px;
      font-weight: 600;
      margin: 0 0 8px 0;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }
    
    .article-summary {
      color: #666;
      margin: 0 0 12px 0;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      flex: 1;
    }
    
    .article-meta {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;
      font-size: 14px;
      color: #666;
      
      .meta-left {
        display: flex;
        align-items: center;
        gap: 8px;
      }
      
      .meta-right {
        display: flex;
        gap: 16px;
        
        span {
          display: flex;
          align-items: center;
          gap: 4px;
        }
      }
    }
    
    .article-tags {
      display: flex;
      gap: 4px;
      flex-wrap: wrap;
    }
  }
}

.sidebar {
  .hot-articles {
    .hot-article-item {
      display: flex;
      gap: 12px;
      padding: 8px 0;
      cursor: pointer;
      
      &:hover {
        background: #f8f9fa;
      }
      
      .rank {
        width: 20px;
        height: 20px;
        background: #007bff;
        color: white;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 12px;
        flex-shrink: 0;
      }
      
      .hot-article-info {
        flex: 1;
        
        h4 {
          margin: 0 0 4px 0;
          font-size: 14px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        
        p {
          margin: 0;
          font-size: 12px;
          color: #666;
        }
      }
    }
  }
  
  .hot-tags {
    line-height: 1.8;
  }
}

.load-more {
  text-align: center;
  margin: 20px 0;
}

@media (max-width: 768px) {
  .article-container {
    grid-template-columns: 1fr;
    padding: 12px;
  }
  
  .article-card {
    flex-direction: column;
    
    .article-cover {
      width: 100%;
      height: 200px;
    }
  }
}
</style>
